<template>
	<view>
		<!-- 输入框，用于显示选中的月份 -->
		<view class="" @click="handlePicker">
			<view class="down-menu">
				<text>{{ currentMonth }}月</text>
				<image src="/static/images/index/down.png" class="width-12 height-12" mode=""></image>
			</view>
		</view>

		<!-- 弹出层 -->
		<Popup :show.sync="showPopup" title="选择月份">
			<view class="">
				<!-- 月份选择器 -->
				<van-picker :columns="monthColumns" :default-index="translatePicker" ref="picker" />
				<view class="self-btn" hover-class="pressed" @click="handleConfirm">
					<text>确定</text>
				</view>
			</view>
		</Popup>
	</view>
</template>

<script>
	import dayjs from 'dayjs';
	import Popup from "@/components/popup/index.vue";

	export default {
		props: {
			// 双向绑定的值
			value: {
				type: [String, Number],
				default: ''
			},
			// 必传的年份参数
			year: {
				type: [String, Number],
				required: true,
				default: () => dayjs().format('YYYY') // 默认当前年份
			}
		},
		components: {
			Popup
		},
		data() {
			return {
				showPopup: false, // 控制弹出层的显示
				monthColumns: [], // 月份列表
				currentMonth: this.value || dayjs().format('M') // 当前选中的月份
			};
		},
		computed: {
			// 计算默认选中的月份索引
			translatePicker() {
				return this.monthColumns.findIndex(item => item.value == this.currentMonth) || 0;
			}
		},
		watch: {
			// 监听外部传入的 value 值变化
			value: {
				immediate: true,
				handler(val) {
					this.currentMonth = val;
					if (!this.monthColumns.length) {
						this.generateMonthColumns();
					}
				}
			},
			// 监听年份变化，重新生成月份列表并调整选中月份
			year: {
				immediate: true,
				handler(newYear) {
					// 先生成新的月份列表
					this.generateMonthColumns();
					// 再调整选中月份
					this.adjustMonthOnYearChange(newYear);
				}
			}
		},
		methods: {
			// 打开选择器
			handlePicker() {
				this.showPopup = true;
			},
			// 调整选中月份（年份变化时）
			adjustMonthOnYearChange(newYear) {
				const currentYear = dayjs().format('YYYY');
				const currentMonth = dayjs().format('M');

				// 根据年份类型处理月份
				if (newYear > currentYear) {
					// 未来年份强制设为1月
					this.currentMonth = '1';
				} else if (newYear === currentYear) {
					// 当前年份不能超过当前月
					if (Number(this.currentMonth) > currentMonth) {
						this.currentMonth = String(currentMonth);
					}
				} else {
					// 过去年份确保在1-12范围内
					const monthNum = Number(this.currentMonth);
					if (monthNum < 1 || monthNum > 12) {
						this.currentMonth = '12';
					}
				}

				// 最终确保在生成的月份列表范围内
				const maxValue = this.monthColumns.length > 0 ?
					Number(this.monthColumns[this.monthColumns.length - 1].value) :
					12;

				if (Number(this.currentMonth) > maxValue) {
					this.currentMonth = String(maxValue);
				}

				this.$emit('input', this.currentMonth);
			},

			// 生成月份列表（已优化）
			generateMonthColumns() {
				const currentYear = dayjs().format('YYYY');
				const currentMonth = dayjs().format('M');

				// 根据年份决定最大月份
				const maxMonth = this.year == currentYear ? currentMonth : 12;

				this.monthColumns = Array.from({
					length: maxMonth
				}, (_, i) => ({
					text: `${i + 1}月`,
					value: String(i + 1)
				}));
			},
			// 选择器变化事件
			// handlePickerChange(picker) {
			// 	this.currentMonth = picker.detail.value.value;
			// },
			// 确认选择
			handleConfirm() {
				let values = this.$refs.picker.getValues()
				this.currentMonth = values[0]['value']
				this.$emit('input', this.currentMonth); // 触发 input 事件，实现双向绑定
				this.showPopup = false; // 关闭弹出层
			}
		}
	};
</script>
<style scoped lang="scss">
	/* 自定义样式 */
	.down-menu {
		min-width: 176rpx;
		box-sizing: border-box;
		background: #FFFFFF;
		border-radius: 32rpx;
		border: 1rpx solid #DDE0E6;
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-weight: 400;
		font-size: 24rpx;
		color: #202020;
		line-height: 32rpx;
		padding: 16rpx 24rpx;

		&>image {
			margin-left: 26rpx;
		}
	}
</style>